package com.demo.petshop.service.impl;

import com.demo.petshop.util.JwtUtil;
import com.demo.petshop.util.Result;
import com.mybatisflex.core.query.QueryWrapper;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.demo.petshop.entity.Users;
import com.demo.petshop.mapper.UsersMapper;
import com.demo.petshop.service.UsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.sqlite.date.DateFormatUtils;
import static com.demo.petshop.entity.table.UsersTableDef.USERS;

import java.util.Date;
import java.util.Map;

/**
 *  服务层实现。
 *
 * @author lenovo
 * @since 2025-06-09
 */
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private AuthenticationManager authenticationManager;

    private int getUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        return loginUser.getUser().getUserId();
    }

    @Override
    public Object login(Users users) {
        UsernamePasswordAuthenticationToken authenticationToken  =
                new UsernamePasswordAuthenticationToken(users.getUsername(), users.getPasswordHash());
        Authentication auth = authenticationManager.authenticate(authenticationToken);
        LoginUser loginUser = (LoginUser) auth.getPrincipal();
        Users ret = loginUser.getUser();
        ret.setPasswordHash(JwtUtil.generateToken(ret));
        return Result.success(ret);
    }

    @Override
    public Object register(Users user) {
        if(usersMapper.selectOneByQuery(new QueryWrapper()
                .where(USERS.PHONE.eq(user.getPhone()))) != null){
            return Result.fail("手机号已被注册");
        }
        BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
        user.setPasswordHash(encoder.encode(user.getPasswordHash()));
        user.setCreatedAt(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        user.setUpdatedAt(DateFormatUtils.format(new Date(),"yyyy-MM-dd HH:mm:ss"));
        return Result.success(usersMapper.insert(user));
    }

    @Override
    public Object checkLog() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        LoginUser loginUser = (LoginUser) authentication.getPrincipal();
        Users ret = loginUser.getUser();
        ret.setPasswordHash(JwtUtil.generateToken(ret));
        return Result.success(ret);
    }
    
    @Override
    public Object getUserProfile() {
        try {
            int userId = getUserId();
            Users user = getById(userId);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            // 隐藏密码等敏感信息
            user.setPasswordHash(null);
            return Result.success(user);
        } catch (Exception e) {
            return Result.checkFailed();
        }
    }
    
    @Override
    public Object updateUserProfile(Map<String, Object> userData) {
        try {
            int userId = getUserId();
            Users user = getById(userId);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            
            // 更新可修改的用户资料字段
            if (userData.containsKey("nickname")) {
                user.setNickname((String) userData.get("nickname"));
            }
            
            if (userData.containsKey("bio")) {
                user.setBio((String) userData.get("bio"));
            }
            
            if (userData.containsKey("gender")) {
                user.setGender((String) userData.get("gender"));
            }
            
            if (userData.containsKey("birthday")) {
                user.setBirthday((String) userData.get("birthday"));
            }
            
            if (userData.containsKey("phone")) {
                // 验证手机号是否已存在
                Users existingUser = usersMapper.selectOneByQuery(new QueryWrapper()
                        .where(USERS.PHONE.eq((String) userData.get("phone"))));
                if (existingUser != null && !existingUser.getUserId().equals(userId)) {
                    return Result.fail("手机号已被其他用户使用");
                }
                user.setPhone((String) userData.get("phone"));
            }
            
            user.setUpdatedAt(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            usersMapper.update(user);
            
            return Result.success(user);
        } catch (Exception e) {
            return Result.checkFailed();
        }
    }
    
    @Override
    public Object updatePassword(Map<String, Object> passwordData) {
        try {
            int userId = getUserId();
            Users user = getById(userId);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            
            String password = (String) passwordData.get("password");
            if (password == null || password.isEmpty()) {
                return Result.fail("密码不能为空");
            }
            
            // 如果前端提供了旧密码，进行验证
            if (passwordData.containsKey("oldPassword")) {
                String oldPassword = (String) passwordData.get("oldPassword");
                BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
                if (!encoder.matches(oldPassword, user.getPasswordHash())) {
                    return Result.wrongPassword();
                }
            }
            
            // 更新密码
            BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
            user.setPasswordHash(encoder.encode(password));
            user.setUpdatedAt(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            usersMapper.update(user);
            
            return Result.success("密码更新成功");
        } catch (Exception e) {
            return Result.checkFailed();
        }
    }
    
    @Override
    public Object updateUserSettings(Map<String, Object> settingsData) {
        try {
            int userId = getUserId();
            Users user = getById(userId);
            if (user == null) {
                return Result.fail("用户不存在");
            }
            
            // 更新生物识别设置
            if (settingsData.containsKey("use_biometric")) {
                user.setUseBiometric((Integer) settingsData.get("use_biometric"));
            }
            
            if (settingsData.containsKey("biometric_type")) {
                user.setBiometricType((String) settingsData.get("biometric_type"));
            }
            
            // 更新通知设置
            if (settingsData.containsKey("notifications_enabled")) {
                user.setNotificationsEnabled((Integer) settingsData.get("notifications_enabled"));
            }
            
            user.setUpdatedAt(DateFormatUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            usersMapper.update(user);
            
            return Result.success("设置更新成功");
        } catch (Exception e) {
            return Result.checkFailed();
        }
    }
    
    @Override
    public Object clearUserCache() {
        try {
            // 这里可以添加实际的缓存清理逻辑，如清除Redis缓存等
            // 当前只是模拟成功返回
            return Result.success("缓存已清除");
        } catch (Exception e) {
            return Result.fail("清除缓存失败");
        }
    }
}
